# coding=utf-8
from werkzeug.routing import BaseConverter
from flask import session,jsonify,g
from iHome.response_code import RET
import functools


# 自定义路由转换器类
class RegexConverter(BaseConverter):
    def __init__(self, url_map, regex):
        super(RegexConverter, self).__init__(url_map)

        # 保存匹配规则的正则表达式
        self.regex = regex


# 登录验证装饰器
def login_required(view_func):
    @functools.wraps(view_func)
    def wrapper(*args,**kwargs):
        user_id = session.get('user_id')
        # 将user_id保存在g变量中
        g.user_id = user_id
        if user_id:
            return view_func(*args,**kwargs)
        else:
            return jsonify(errno=RET.SESSIONERR, errmsg='请先登录')
    return wrapper
